package com.als.healthymananger.handler;

import com.als.healthymananger.utils.RespBean;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 全局异常管理器
 * 在controller中发生的异常都将在这里被捕获
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 数据验证失败
     * 返回具体失败原因
     * @param ex
     * @return
     */
    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    @ResponseBody
    public RespBean validError(MethodArgumentNotValidException ex) {

        BindingResult bindingResult = ex.getBindingResult();

        // 将具体验证失败数据添加到map中
        Map<String, Object> map = new HashMap<>();
        for(FieldError error: bindingResult.getFieldErrors()) {
            String field = error.getField();
            String message = error.getDefaultMessage();
            map.put(field, message);
        }

        // 实例化公共返回对象
        RespBean respBean = new RespBean();
        respBean.setCode(412);
        respBean.setMessage("数据验证失败");
        respBean.setData(map);

        return respBean;
    }

    /**
     * 未找到资源异常处理
     * @return
     */
    @ExceptionHandler(value = {Exception.class})
    @ResponseBody
    public RespBean notFoundError() {
        return new RespBean(404, "未找到相应资源", null);
    }
}
